package com.thon.controller.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import java.util.Date;

import javax.imageio.ImageIO;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.multipart.MultipartFile;

import com.thon.Application;
import com.thon.commons.config.Global;
import com.thon.commons.utils.ImageUtil;
import com.thon.commons.utils.PropertiesLoader;
import com.thon.controller.rest.AlipayRestController;
import com.thon.entity.user.Attachment;
import com.thon.entity.user.User;

/**
 * @author manpiaoyi
 * @email manpiaoyi@126.com
 * @date 2014-10-13
 * @description:
 */
public final class AttachmentUtil {
	
	private static final String basePath = SystemUtils.getUserHome() + "/." +  PropertiesLoader.getConfiguration("application.properties", "project.name") + "/attachments";

	private static final String pressText=Global.getConfig("press.text");
	
	private static final Log log = LogFactory.getLog(AttachmentUtil.class);
	public static void read(Attachment attachment) {
		try {
		    // 默认图片
			File blankFile = new File(basePath, "not_exist.jpg");
			if (!blankFile.exists()) {
				Font font = new Font("Serif", Font.BOLD, 400);
				ImageUtil.newBlankImage("?", blankFile, font, 800, 800);
			}
		
			// 存在记录，则找到目标图片或缩略图
			File targetFile = getTargetFile(attachment);
			if(targetFile.exists() && attachment.getId() != null && !StringUtils.equalsIgnoreCase(attachment.getSuffix(), ".gif") && StringUtils.isNotBlank(attachment.getDimension())) {
				File thumnailFile = getThumnailFile(attachment);
				if(!thumnailFile.exists()) {
					ImageUtil.resize(targetFile, thumnailFile, attachment.getDimension(), attachment.getSuffix().substring(1));
				}
				blankFile = thumnailFile;
			}else if(targetFile.exists() && (StringUtils.isBlank(attachment.getDimension()) || StringUtils.equalsIgnoreCase(attachment.getSuffix(), ".gif"))) {
				blankFile = targetFile;
			}
			
			attachment.setBytes(FileUtils.readFileToByteArray(blankFile));	
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void write(Attachment attachment,Boolean press){
		File targetFile = getTargetFile(attachment);
		String contentType = attachment.getContentType();
		String type =  contentType.substring(0, contentType.indexOf("/"));
		try {
			if (type.equals("image") && press) {
				String targetImg = getTargetFilePath(attachment);
				FileUtils.writeByteArrayToFile(targetFile, attachment.getBytes());
				ImageUtil.pressText(pressText, targetImg, "SimSun", Font.PLAIN, Color.white, 15, 0, 0, 0.8f);
			}else{
				FileUtils.writeByteArrayToFile(targetFile, attachment.getBytes());
			}
		} catch (IOException e) {
		}
	}
	
	public static Attachment parse(MultipartFile file, String contentType, int userId){
		Attachment attachment = new Attachment();
		User user = new User();
		user.setId(userId);
		attachment.setUser(user);
		attachment.setContentType(contentType);
		attachment.setFileName(file.getOriginalFilename());
		attachment.setFileSize(((Long)file.getSize()).intValue());
		try {
			attachment.setBytes(file.getBytes());
		} catch (IOException e) {
		}
		attachment.setCreatedDate(new Date());
		
		return attachment;
	}
	
	public static Attachment parse(byte[] fileData, String contentType, String fileName, Integer fileSize, User user){
		Attachment attachment = new Attachment();
		attachment.setContentType(contentType);
		attachment.setFileName(fileName);
		attachment.setFileSize(fileSize);
		attachment.setBytes(fileData);
		attachment.setUser(user);
		attachment.setCreatedDate(new Date());
		
		return attachment;
	}
	
	public static void delete(Attachment attachment) {
		File targetFile = getTargetFile(attachment);
		if(StringUtils.isNotBlank(attachment.getDimension())) {
			File thumnailFile = getThumnailFile(attachment);
			FileUtils.deleteQuietly(thumnailFile);
		}
		FileUtils.deleteQuietly(targetFile);
	}
	
	// 获取缩略图
	private static File getThumnailFile(Attachment attachment) {
		StringBuffer pathBuffer = new StringBuffer(basePath);
		pathBuffer.append("/" + DateFormatUtils.format(attachment.getCreatedDate(), "yyyy"));
		pathBuffer.append("/" + DateFormatUtils.format(attachment.getCreatedDate(), "MMdd"));
		String name = attachment.getName() + "_" + attachment.getId() + "." +attachment.getDimension() + attachment.getSuffix();
		return new File(pathBuffer.toString(), name);
	}
	
	// 获取全图
	public static File getTargetFile(Attachment attachment) {
		StringBuffer pathBuffer = new StringBuffer(basePath);
		pathBuffer.append("/" + DateFormatUtils.format(attachment.getCreatedDate(), "yyyy"));
		pathBuffer.append("/" + DateFormatUtils.format(attachment.getCreatedDate(), "MMdd"));
		String name =  attachment.getName() + "_" + attachment.getId() + attachment.getSuffix();
		return new File(pathBuffer.toString(), name);
	}
	
	public static String getTargetFilePath(Attachment attachment) {
		StringBuffer pathBuffer = new StringBuffer(basePath);
		pathBuffer.append("/" + DateFormatUtils.format(attachment.getCreatedDate(), "yyyy"));
		pathBuffer.append("/" + DateFormatUtils.format(attachment.getCreatedDate(), "MMdd"));
		String name = pathBuffer+ "/"+attachment.getName() + "_" + attachment.getId() + attachment.getSuffix();
		return name;
	}

}